package com.syni.mdd.yhd.common.all.service;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.sjb.common.component.utils.common.utils.BeanUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ParamsMap;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsbusinessDao;
import com.syni.mdd.yhd.common.all.dto.requestDto.business.BusinessReDto;
import com.syni.mdd.yhd.common.all.entity.*;
import com.syni.mdd.yhd.common.all.entity.coupon.BmsFullCoupon;
import com.syni.mdd.yhd.common.all.entity.groupChat.BmsDxGroupChat;
import com.syni.mdd.yhd.common.all.listen.business.BusinessFrontPageEvent;
import com.syni.mdd.yhd.common.all.listen.business.BusinessUpdateDataEvent;
import com.syni.mdd.yhd.common.all.listen.focus.BusinessFocusEvent;
import com.syni.mdd.yhd.common.all.service.impl.BaseService;
import com.syni.mdd.yhd.common.all.utils.LocationUtils;
import com.syni.mdd.yhd.common.all.utils.SpecificationUtils;
import com.syni.mdd.yhd.common.all.utils.StringUtils;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiBusiness.CreateBusinessDto;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiBusiness.UpdateBusinessDto;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiBusiness.CreateBusinessDto;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @className BmsUserOperationLogService
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/9 12:04
 * @VERSION 1.0
 **/
@Service
@Log4j2
public class BmsBusinessService extends BaseService<BmsBusiness, Integer> {

    public final static int IS_AUTH = 1;

    @Autowired
    BmsbusinessDao bmsbusinessDao;

    @Autowired
    BmsVideoService bmsVideoService;

    @Autowired
    BmsUserBusinessAuthService bmsUserBusinessAuthService;

    @Autowired
    BmsUserBusinessService bmsUserBusinessService;

    @Autowired
    BmsBusinessLabelService bmsBusinessLabelService;

    @Autowired
    BmsBusinessTypeService bmsBusinessTypeService;

    @Autowired
    BmsBusinessTypeRelationService bmsBusinessTypeRelationService;

    @Autowired
    BmsUserBusinessFocusService bmsUserBusinessFocusService;

    @Autowired
    BmsBusinessHomeVisitService bmsBusinessHomeVisitService;

    @Autowired
    BmsDxOrderService bmsDxOrderService;

    @Autowired
    BmsDxCouponService bmsDxCouponService;

    @Autowired
    BmsDxGroupBuyService bmsDxGroupBuyService;

    @Autowired
    BmsFullCouponService bmsFullCouponService;

    @Autowired
    BmsDxGroupChatService bmsDxGroupChatService;

    @Autowired
    BmsMarketActivityService bmsMarketActivityService;

    @Autowired
    BmsGroupBuyTemplateService bmsGroupBuyTemplateService;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public BmsbusinessDao getBaseDao() {
        return bmsbusinessDao;
    }

    public Map<Integer,BmsBusiness> findBusinessByIds(Set<Integer> ids){
        Map<Integer,BmsBusiness> bmsBusinessMap = new HashMap<>();
        if(ids.size() > 0) {
            List<BmsBusiness> bmsBusinesses = bmsbusinessDao.findByIdIn(ids);
            if (bmsBusinesses != null && bmsBusinesses.size() > 0) {
                setIsOpenCouponAndGroupBuy(bmsBusinesses);
                for (BmsBusiness business : bmsBusinesses) {
                    bmsBusinessMap.put(business.getId(), business);
                }
            }
        }
        return bmsBusinessMap;
    }

    public Map<Integer,BmsBusiness> findBusinessByIdsIgnoreSetBuyCoupon(Set<Integer> ids){
        Map<Integer,BmsBusiness> bmsBusinessMap = new HashMap<>();
        if(ids.size() > 0) {
            List<BmsBusiness> bmsBusinesses = bmsbusinessDao.findByIdIn(ids);
            if (bmsBusinesses != null && bmsBusinesses.size() > 0) {
                for (BmsBusiness business : bmsBusinesses) {
                    bmsBusinessMap.put(business.getId(), business);
                }
            }
        }
        return bmsBusinessMap;
    }

    @Transactional
    public Map<String, Object> findBussinessIndex(String userId,Integer businessId,
                                                  String latitude,String longitude,Integer pageSize){
        Integer defaultPage = 1;
        Optional<BmsBusiness> businessOp = bmsbusinessDao.findById(businessId);
        if(!businessOp.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST,"商家不存在");
        }
        BmsBusiness business = businessOp.get();
        //设置当前用户是否关注
        if(userId != null) {
            if(bmsUserBusinessFocusService.checkUserIsFocusBusiness(Integer.parseInt(userId),businessId)){
                business.setIsUserFocus(Integer.parseInt(Constants.COMMON_FLAG_TRUE));
            }
        }
        //查询是否设置优惠买单
        if(bmsDxCouponService.checkIsOpenCoupon(businessId)){
            business.setIsOpenCoupon(Constants.COMMON_FLAG_TRUE_INT);
        }
        //查询是否设置团购
        if(bmsDxGroupBuyService.checkIsOpenGroupBuy(businessId)){
            business.setIsOpenGroupBuy(Constants.COMMON_FLAG_TRUE_INT);
        }
        //查询是否有活动
        if(bmsMarketActivityService.checkIsHavingActivity(businessId)){
            business.setIsOpenActivity(Constants.COMMON_FLAG_TRUE_INT);
        }
        //查询该首家标签id
        if(pageSize > Constants.COMMON_FLAG_FALSE_INT) {
            Pageable pageable = PageRequest.of(defaultPage - 1, pageSize, Sort.Direction.DESC, "isTop", "updateTime", "newTime");
            List<BmsVideo> bmsVideos = this.findBusinessVideoToUserClient(userId, businessId, latitude, longitude, pageable);
            business.setBmsVideos(bmsVideos);
        }
        //将对该商家的访问添加进访问记录表
        addBusinessHomeVisit(userId,businessId,business.getVendorName());
        //查询是否有满减券
        List<BmsFullCoupon> bmsFullCoupons = bmsFullCouponService.getBaseDao().findByBusinessIdAndIsDisplay(businessId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsFullCoupons != null && bmsFullCoupons.size() > 0){
            BmsFullCoupon bmsFullCoupon = bmsFullCoupons.get(0);
            business.setBmsFullCoupon(bmsFullCoupon);
            /*Integer nowTime = (int)(System.currentTimeMillis() / 1000);
            Integer startTime = (int)(bmsFullCoupon.getStartTime().getTime() / 1000);
            Integer endTime = (int)(DateTimeUtils.addDay(bmsFullCoupon.getEndTime(),1).getTime() / 1000);
            if(nowTime >= startTime && nowTime < endTime) {
                business.setBmsFullCoupon(bmsFullCoupon);
            }*/
        }
        //查询是否有群聊
        setBusinessGroupChat(business);
        BmsCommonService.getApplicationContext().publishEvent(new BusinessFrontPageEvent("frontPageEvent",business,userId));
        return ResultMapHelper.success(business,"获取成功");
    }

    private void setBusinessGroupChat(BmsBusiness business) {
        List<BmsDxGroupChat> bmsDxGroupChats = bmsDxGroupChatService.getBaseDao().findByBusinessIdAndIsDelete(business.getId(),Constants.COMMON_FLAG_FALSE_INT);
        if(bmsDxGroupChats != null && bmsDxGroupChats.size() > 0){
            BmsDxGroupChat bmsDxGroupChat = bmsDxGroupChats.get(0);
            business.setBmsDxGroupChat(bmsDxGroupChat);
        }
    }

    public void addBusinessHomeVisit(String userId,Integer businessId,String vendorName){
        BmsBusinessHomeVisit bmsBusinessHomeVisit = new BmsBusinessHomeVisit();
        if(userId == null) {
            bmsBusinessHomeVisit.setBmsUserId(null);
        }else {
            bmsBusinessHomeVisit.setBmsUserId(Integer.parseInt(userId));
        }
        bmsBusinessHomeVisit.setBmsBusinessId(businessId);
        bmsBusinessHomeVisit.setNewTime(new Date());
        bmsBusinessHomeVisitService.save(bmsBusinessHomeVisit);
    }

    public void setBusinessTagId(BmsBusiness business){
        if(business != null){
            List<BmsBusinessTypeRelation> bmsBusinessTypeRelations = bmsBusinessTypeRelationService.getBaseDao().findByBmsBusinessId(business.getId());
            if(bmsBusinessTypeRelations != null && bmsBusinessTypeRelations.size() > 0){
                business.setTagsId(bmsBusinessTypeRelations.get(0).getBmsTypeId());
            }
        }
    }

    public Map<String,Object> findBusinessToFront(String addrCity,String searchText,
                                                  Integer pageNum,Integer pageSize){
        Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"dk_times","new_time");
        List<Map<String,Object>> resultList = bmsbusinessDao.findByVendorNameToMerchant(searchText,addrCity,Integer.parseInt(Constants.COMMON_FLAG_FALSE),
                Integer.parseInt(Constants.COMMON_FLAG_FALSE),pageable);
        return ResultMapHelper.success(resultList,"获取成功");
    }

    public List<BmsBusiness> getCanClaimBusiness(String addrCity,String searchText,Set<Integer> typeIds,
                                                  Integer pageNum,Integer pageSize){
        Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"dk_times","new_time");
        List<Map<String,Object>> resultList = bmsbusinessDao.findByVendorNameToDank(searchText,addrCity,typeIds,Constants.COMMON_FLAG_FALSE_INT,
                Constants.COMMON_FLAG_FALSE_INT,pageable);
        List<BmsBusiness> bmsBusinesses = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(resultList)){
            for(Map<String,Object> data : resultList){
                BmsBusiness bmsBusiness = new BmsBusiness();
                bmsBusiness.setId(Integer.parseInt(data.get("id").toString()));
                if(data.containsKey("vendorName") && StringUtils.checkNullAndEmpty(data.get("vendorName"))){
                    bmsBusiness.setVendorName(data.get("vendorName").toString());
                }
                if(data.containsKey("addrDetails") && StringUtils.checkNullAndEmpty(data.get("addrDetails"))){
                    bmsBusiness.setAddrDetails(data.get("addrDetails").toString());
                }
                bmsBusinesses.add(bmsBusiness);
            }
        }
        return bmsBusinesses;
    }

    public List<BmsBusiness> getCanClaimBusiness(String addrCity,String searchText,
                                                 Integer pageNum,Integer pageSize){
        Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"dk_times","new_time");
        List<Map<String,Object>> resultList = bmsbusinessDao.findByVendorNameToMerchant(searchText,addrCity,Constants.COMMON_FLAG_FALSE_INT,
                Constants.COMMON_FLAG_FALSE_INT,pageable);
        List<BmsBusiness> bmsBusinesses = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(resultList)){
            resultList.forEach(obj -> {
                BmsBusiness bmsBusiness = new BmsBusiness();
                bmsBusiness.setId(Integer.parseInt(obj.get("id").toString()));
                bmsBusiness.setVendorName(obj.get("vendorName").toString());
                bmsBusiness.setAddrDetails(obj.get("addrDetails").toString());
                bmsBusinesses.add(bmsBusiness);

            });
        }
        return bmsBusinesses;
    }


    public Integer countCanClaimBusiness(String addrCity,String searchText,Set ids){
        return bmsbusinessDao.countByVendorNameToMerchant(searchText,addrCity,ids,Constants.COMMON_FLAG_FALSE_INT,Constants.COMMON_FLAG_FALSE_INT);
    }

    public Integer countCanClaimBusiness(String addrCity,String searchText){
        return bmsbusinessDao.countByVendorNameToMerchant(searchText,addrCity,Constants.COMMON_FLAG_FALSE_INT,Constants.COMMON_FLAG_FALSE_INT);
    }


    public Map<String, Object> findBusinessToReleaseVideo(String businessName,String addrCity,String addrDistrict,
                                                          Integer pageNum,Integer pageSize) {
        List<BmsBusiness> bmsBusinesses = new LinkedList<>();
        if(!"".equals(businessName)) {
            Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC, "dkTimes", "newTime");
            Map<String,Object> conditionMap = new HashMap<>();
            conditionMap.put("vendorName_LIKE",businessName);
            conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
            conditionMap.put("isUnload",Constants.COMMON_FLAG_FALSE_INT);
            if(StringUtils.isNotBlank(addrCity)){
                conditionMap.put("addrCity",addrCity);
            }
            if(StringUtils.isNotBlank(addrDistrict)){
                conditionMap.put("addrDistrict",addrDistrict);
            }
            bmsBusinesses.addAll(bmsbusinessDao.findAll(new SpecificationUtils(conditionMap),pageable).getContent());
        }
        setLabels(bmsBusinesses);
        return ResultMapHelper.success(bmsBusinesses);
    }

    /*@Transactional
    public Map<String, Object> createBusiness(Integer userId,String businessName,String businessHour,String addr,
                                              String addrDetail,String latitude,String longitude,String phone,Integer labelId) {
        Pageable pageable = BmsCommonService.getPageable(1,1);
        Page<BmsBusiness> bmsBusinesses = bmsbusinessDao.findAll(new Specification<BmsBusiness>() {
            @Override
            public Predicate toPredicate(Root<BmsBusiness> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                predicates.add(criteriaBuilder.equal(root.get("vendorName").as(String.class),businessName));
                predicates.add(criteriaBuilder.equal(root.get("isDelete").as(Integer.class),Integer.parseInt(Constants.COMMON_FLAG_FALSE)));
                predicates.add(criteriaBuilder.equal(root.get("isUnload").as(Integer.class),Integer.parseInt(Constants.COMMON_FLAG_FALSE)));
                criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
        if(bmsBusinesses.getContent().size() > 0){
            return ResultMapHelper.failure("已有该商家存在");
        }
        BmsBusiness business = new BmsBusiness();
        business.setVendorName(businessName);
        business.setAddrDetails(addrDetail);
        business.setPhone(phone);
        business.setBusinessHours(businessHour);
        business.setLatitude(latitude);
        business.setLongitude(longitude);
        if(StringUtils.isNotBlank(addr)){
            try {
                String[] addrData = addr.split("_");
                business.setAddrProvince(addrData[0]);
                business.setAddrCity(addrData[1]);
                business.setAddrDistrict(addrData[2]);
            }catch (Exception e){log.error(e.getMessage(),e);}
        }
        business.setNewTime(new Date());
        business.setIsDelete(Integer.parseInt(Constants.COMMON_FLAG_FALSE));
        business.setDkTimes(Integer.parseInt(Constants.COMMON_FLAG_FALSE));
        business.setIsAuth(Integer.parseInt(Constants.COMMON_FLAG_FALSE));
        business.setIsUnload(Integer.parseInt(Constants.COMMON_FLAG_FALSE));
        business.setOperatingState(Constants.COMMON_FLAG_FALSE_INT);
        bmsbusinessDao.save(business);
        //查出标签名称
        if(labelId != null) {
            Optional<BmsBusinessLabel> bmsBusinessLabelOp = bmsBusinessLabelService.getBaseDao().findById(labelId);
            if (bmsBusinessLabelOp.isPresent()) {
                BmsBusinessLabel bmsBusinessLabel = bmsBusinessLabelOp.get();
                Integer typeId = bmsBusinessLabel.getTypeId();
                Optional<BmsBusinessType> bmsBusinessTypeOptional = bmsBusinessTypeService.getBaseDao().findById(typeId);
                if (bmsBusinessTypeOptional.isPresent()) {
                    BmsBusinessType bmsBusinessType = bmsBusinessTypeOptional.get();
                    business.setTags(bmsBusinessType.getTypeName());
                    bmsBusinessTypeRelationService.addBusinessRelation(business.getId(), bmsBusinessType.getId());
                }
                business.setLabel(bmsBusinessLabelOp.get().getLabelName());
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("business",business);
        return ResultMapHelper.success(resultMap,"创建成功");
    }*/


    @Transactional
    public Map<String, Object> createBusiness(ParamsMap paramsMap) {
        Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        String businessName = paramsMap.get("business_name").toString();
        String addr = paramsMap.get("addr").toString();
        String addrDetail = paramsMap.get("addr_detail").toString();
        final int MAX_ADDR_DETAIL = 200;
        if(addrDetail.length() >= MAX_ADDR_DETAIL){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_03,"地址内容过长");
        }
        String latitude = paramsMap.get("latitude").toString();
        String longitude = paramsMap.get("longitude").toString();
        Integer labelId = paramsMap.getInteger("label_id");
        String phone = paramsMap.get("phone").toString();
        String businessHour = "";
        if(paramsMap.containsKey("business_hour") && !"".equals(paramsMap.get("business_hour").toString())){
            businessHour = paramsMap.get("business_hour").toString();
        }
        Integer typeId = paramsMap.getInteger("typeId");
        Pageable pageable = BmsCommonService.getPageable(1,1);
        Page<BmsBusiness> bmsBusinesses = bmsbusinessDao.findAll(new Specification<BmsBusiness>() {
            @Override
            public Predicate toPredicate(Root<BmsBusiness> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                predicates.add(criteriaBuilder.equal(root.get("vendorName").as(String.class),businessName));
                predicates.add(criteriaBuilder.equal(root.get("isDelete").as(Integer.class),Integer.parseInt(Constants.COMMON_FLAG_FALSE)));
                predicates.add(criteriaBuilder.equal(root.get("isUnload").as(Integer.class),Integer.parseInt(Constants.COMMON_FLAG_FALSE)));
                criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
        if(bmsBusinesses.getContent().size() > 0){
            return ResultMapHelper.failure("已有该商家存在");
        }
        BmsBusiness business = new BmsBusiness();
        business.setVendorName(businessName);
        business.setAddrDetails(addrDetail);
        business.setPhone(phone);
        business.setBusinessHours(businessHour);
        business.setLatitude(latitude);
        business.setLongitude(longitude);
        if(StringUtils.isNotBlank(addr)){
            try {
                String[] addrData = addr.split("_");
                business.setAddrProvince(addrData[0]);
                business.setAddrCity(addrData[1]);
                business.setAddrDistrict(addrData[2]);
            }catch (Exception e){log.error(e.getMessage(),e);}
        }
        business.setNewTime(new Date());
        business.setIsDelete(Integer.parseInt(Constants.COMMON_FLAG_FALSE));
        business.setDkTimes(Integer.parseInt(Constants.COMMON_FLAG_FALSE));
        business.setIsAuth(Integer.parseInt(Constants.COMMON_FLAG_FALSE));
        business.setIsUnload(Integer.parseInt(Constants.COMMON_FLAG_FALSE));
        business.setOperatingState(Constants.COMMON_FLAG_FALSE_INT);
        bmsbusinessDao.save(business);
        //查出标签名称
        if(labelId != null) {
            Optional<BmsBusinessLabel> bmsBusinessLabelOp = bmsBusinessLabelService.getBaseDao().findById(labelId);
            if (bmsBusinessLabelOp.isPresent()) {
                business.setLabel(bmsBusinessLabelOp.get().getLabelName());
                if(typeId == null){
                    typeId = bmsBusinessLabelOp.get().getTypeId();
                }
            }
        }
        if(typeId != null) {
            Optional<BmsBusinessType> bmsBusinessTypeOptional = bmsBusinessTypeService.getBaseDao().findById(typeId);
            if (bmsBusinessTypeOptional.isPresent()) {
                BmsBusinessType bmsBusinessType = bmsBusinessTypeOptional.get();
                business.setTags(bmsBusinessType.getTypeName());
                business.setTagsId(typeId);
                bmsBusinessTypeRelationService.addBusinessRelation(business.getId(), bmsBusinessType.getId());
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("business",business);
        return ResultMapHelper.success(resultMap,"创建成功");
    }

    public Map<String,Object> createBusiness(CreateBusinessDto createBusinessDto) {
        String addrDetail = createBusinessDto.getAddrDetails();
        final int MAX_ADDR_DETAIL = 200;
        if(addrDetail.length() >= MAX_ADDR_DETAIL){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,"地址内容过长");
        }
        Pageable pageable = BmsCommonService.getPageable(1,1);
        Page<BmsBusiness> bmsBusinesses = bmsbusinessDao.findAll(new Specification<BmsBusiness>() {
            @Override
            public Predicate toPredicate(Root<BmsBusiness> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                predicates.add(criteriaBuilder.equal(root.get("vendorName").as(String.class),createBusinessDto.getVendorName()));
                predicates.add(criteriaBuilder.equal(root.get("isDelete").as(Integer.class),Integer.parseInt(Constants.COMMON_FLAG_FALSE)));
                predicates.add(criteriaBuilder.equal(root.get("isUnload").as(Integer.class),Integer.parseInt(Constants.COMMON_FLAG_FALSE)));
                criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
        if(bmsBusinesses.getContent().size() > 0){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,"已有该商家存在");
        }
        BmsBusiness business = new BmsBusiness();
        BeanUtils.copyProperties(createBusinessDto,business);
        if(createBusinessDto.getLabelId() != null) {
            Optional<BmsBusinessLabel> bmsBusinessLabelOp = bmsBusinessLabelService.getBaseDao().findById(createBusinessDto.getLabelId());
            if (bmsBusinessLabelOp.isPresent()) {
                if(!bmsBusinessLabelOp.get().getTypeId().equals(createBusinessDto.getTypeId())){
                    return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.MSG_BUSINESS_NO_MAPPING_TYPE_LABEL);
                }
                business.setLabel(bmsBusinessLabelOp.get().getLabelName());
            }
        }
        business.setStartHours(DateTimeUtils.converLocalDateTimeToLong(createBusinessDto.getStartHours()));
        business.setEndHours(DateTimeUtils.converLocalDateTimeToLong(createBusinessDto.getEndHours()));
        business.setNewTime(new Date());
        bmsbusinessDao.save(business);
        if(createBusinessDto.getTypeId() != null) {
            Optional<BmsBusinessType> bmsBusinessTypeOptional = bmsBusinessTypeService.getBaseDao().findById(createBusinessDto.getTypeId());
            if (bmsBusinessTypeOptional.isPresent()) {
                BmsBusinessType bmsBusinessType = bmsBusinessTypeOptional.get();
                business.setTags(bmsBusinessType.getTypeName());
                business.setTagsId(createBusinessDto.getTypeId());
                bmsBusinessTypeRelationService.addBusinessRelation(business.getId(), bmsBusinessType.getId());
            }
        }
        bmsbusinessDao.save(business);
        return ResultMapHelper.success(business,"创建成功");
    }

    public Map<String, Object> updateBusiness(UpdateBusinessDto updateBusinessDto) {

        Integer businessId = updateBusinessDto.getBusinessId();
        Optional<BmsBusiness> bmsBusinessOptional = bmsbusinessDao.findById(businessId);
        if(!bmsBusinessOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.CODE_BUSINESS_NO_EXIST);
        }
        BmsBusiness business = bmsBusinessOptional.get();
        //店铺logo
        String logoUrl = updateBusinessDto.getLogoUrl();
        //店铺名称
        String businessName = updateBusinessDto.getVendorName();
        //店铺电话
        String phone = updateBusinessDto.getPhone();
        //营业时间
        String businessHours = updateBusinessDto.getBusinessHours();
        String contactMan = updateBusinessDto.getContactMan();
        //标签
        Integer labelId = updateBusinessDto.getLabelId();
        if(businessName != null){
            if(!businessName.equals(business.getVendorName())){
                //要修改名称了
                Map<String,Object> resultMap = checkIsChangeVendorName(businessId);
                System.out.println(resultMap);
                if(!(ResultCode.CODE_NORMAL.equals(resultMap.get("status").toString()))){
                    return ResultMapHelper.result(ResultCode.CODE_BUSINESS_UPDATE_VDNDOR_NAME_EXPIRE,"半年内只能修改一次店铺名称");
                }
                business.setVendorName(businessName);
                business.setVendorNameUpdateTime(new Date());
            }
        }
        if(StringUtils.isNotBlank(logoUrl)){
            business.setLogoUrl(logoUrl);
        }
        if(StringUtils.isNotBlank(phone)){
            business.setPhone(phone);
        }
        if(StringUtils.isNotBlank(businessHours)){
            business.setBusinessHours(businessHours);
            business.setStartHours(DateTimeUtils.converLocalDateTimeToLong(updateBusinessDto.getStartHours()));
            business.setEndHours(DateTimeUtils.converLocalDateTimeToLong(updateBusinessDto.getEndHours()));
        }

        if(labelId != null){
            Optional<BmsBusinessLabel> bmsBusinessLabel = bmsBusinessLabelService.getBaseDao().findById(labelId);
            if(bmsBusinessLabel.isPresent()){
                List<BmsBusinessTypeRelation> bmsBusinessTypeRelations = bmsBusinessTypeRelationService.getBaseDao().findByBmsBusinessId(businessId);
                //修改店铺标签
                if(bmsBusinessTypeRelations != null && bmsBusinessTypeRelations.size() > 0) {
                    //判断该操作是否修改
                    if (!bmsBusinessTypeRelations.get(0).getBmsTypeId().equals(bmsBusinessLabel.get().getTypeId())) {
                        return ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.MSG_BUSINESS_NO_MAPPING_TYPE_LABEL);
                    }
                }
                business.setLabel(bmsBusinessLabel.get().getLabelName());
                business.setLabelId(bmsBusinessLabel.get().getId());
            }
        }
        if(StringUtils.isNotBlank(contactMan)){
            business.setContactMan(contactMan);
        }
        bmsbusinessDao.save(business);
        bmsBusinessTypeRelationService.postBmsBusinessTypeId(business);
        BeanUtils.copyProperties(business,updateBusinessDto);
        updateBusinessDto.setTypeId(business.getTagsId());
        updateBusinessDto.setStartHours(DateTimeUtils.converDateToLocalDateTime(DateTimeUtils.converLongToDate(business.getStartHours())));
        updateBusinessDto.setEndHours(DateTimeUtils.converDateToLocalDateTime(DateTimeUtils.converLongToDate(business.getEndHours())));
        BmsCommonService.getApplicationContext().publishEvent(new BusinessUpdateDataEvent("updateBusinessData",business));
        return ResultMapHelper.success(updateBusinessDto,"修改成功");
    }

    public Map<String, Object> updateBusiness(ParamsMap paramsMap) {
        Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        Integer businessId = Integer.parseInt(paramsMap.get("business_id").toString());
        //店铺logo
        String logoUrl = paramsMap.getString("logo_url");
        //店铺类型id
        Integer businessTypeId = paramsMap.getInteger("business_type_id");
        //店铺名称
        String businessName = paramsMap.getString("business_name");
        //店铺电话
        String phone = paramsMap.getString("phone");
        //营业时间
        String businessHours = paramsMap.getString("business_hours");
        //标签
        Integer labelId = paramsMap.getInteger("labelId");
        Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHaving(userId,businessId);
        if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
            return checkMap;
        }
        BmsBusiness business = (BmsBusiness) checkMap.get("data");
        if(businessName != null){
            Map<String,Object> resultMap = checkIsChangeVendorName(businessId);
            System.out.println(resultMap);
            if(!(ResultCode.CODE_NORMAL.equals(resultMap.get("status").toString()))){
                return ResultMapHelper.result(ResultCode.CODE_BUSINESS_UPDATE_VDNDOR_NAME_EXPIRE,"半年内只能修改一次店铺名称");
            }
            business.setVendorName(businessName);
            business.setVendorNameUpdateTime(new Date());
        }
        if(logoUrl != null){
            business.setLogoUrl(logoUrl);
        }
        if(businessTypeId != null){
            List<BmsBusinessTypeRelation> bmsBusinessTypeRelations = bmsBusinessTypeRelationService.getBaseDao().findByBmsBusinessId(businessId);
            //修改店铺标签
            if(bmsBusinessTypeRelations != null && bmsBusinessTypeRelations.size() > 0){
                //判断该操作是否修改
                if(bmsBusinessTypeRelations.get(0).getBmsTypeId().intValue() != businessTypeId.intValue()){
                    return ResultMapHelper.result(ResultCode.CODE_BUSINESS_TYPE_CHANGE,ResultMsg.CODE_BUSINESS_TYPE_CHAGE);
                }
            }else {
                //添加关联
                BmsBusinessTypeRelation bmsBusinessTypeRelation = new BmsBusinessTypeRelation();
                bmsBusinessTypeRelation.setBmsBusinessId(businessId);
                bmsBusinessTypeRelation.setBmsTypeId(businessTypeId);
                bmsBusinessTypeRelationService.save(bmsBusinessTypeRelation);
                //添加店铺类型描述
                Set<Integer> typeIds = new HashSet<>();
                typeIds.add(businessTypeId);
                List<BmsBusinessType> bmsBusinessTypes = bmsBusinessTypeService.getBaseDao().findByIdInAndIsDelete(typeIds,Integer.parseInt(Constants.COMMON_FLAG_FALSE));
                if(bmsBusinessTypes != null && bmsBusinessTypes.size() > 0){
                    business.setTags(bmsBusinessTypes.get(0).getTypeName());
                }
            }
        }
        if(phone != null){
            business.setPhone(phone);
        }
        if(businessHours != null){
            business.setBusinessHours(businessHours);
        }
        if(labelId != null){
            Optional<BmsBusinessLabel> bmsBusinessLabel = bmsBusinessLabelService.getBaseDao().findById(labelId);
            if(bmsBusinessLabel.isPresent()){
                business.setLabel(bmsBusinessLabel.get().getLabelName());
                business.setLabelId(bmsBusinessLabel.get().getId());
            }
        }
        bmsbusinessDao.save(business);
        this.setBusinessTagId(business);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("business",business);
        BmsCommonService.getApplicationContext().publishEvent(new BusinessUpdateDataEvent("updateBusinessData",business));
        return ResultMapHelper.success(resultMap,"修改成功");
    }

    public Map<String, Object> focusOnBusiness(Integer userId, Integer businessId,Integer isMandatory) {
        Optional<BmsBusiness> bmsBusiness = bmsbusinessDao.findById(businessId);
        if(!bmsBusiness.isPresent()){
            return ResultMapHelper.failure("关注失败,店铺不存在");
        }
        BmsUserBusinessFocus bmsUserBusinessFocus = bmsUserBusinessFocusService.getBaseDao().findByBmsUserIdAndBmsBusinessId(userId,businessId);
        if(bmsUserBusinessFocus == null){
            bmsUserBusinessFocus = new BmsUserBusinessFocus();
            bmsUserBusinessFocus.setBmsUserId(userId);
            bmsUserBusinessFocus.setBmsBusinessId(businessId);
            bmsUserBusinessFocus.setNewTime(new Date());
            bmsUserBusinessFocusService.save(bmsUserBusinessFocus);
            if(bmsUserBusinessFocus.getId() != null){
                handlePostFocus(bmsBusiness.get(),userId);
                return ResultMapHelper.success("关注成功");
            }
        }else {
            if(isMandatory != null){
                return ResultMapHelper.success("关注成功");
            }
            bmsUserBusinessFocusService.delete(bmsUserBusinessFocus);
            if(!bmsUserBusinessFocusService.getBaseDao().existsById(bmsUserBusinessFocus.getId())){
                return ResultMapHelper.success("取消关注成功");
            }
        }
        return ResultMapHelper.failure(ResultMsg.ADMIN_ERROR);
    }

    public void handlePostFocus(BmsBusiness bmsBusiness,Integer userId){
        BmsCommonService.getApplicationContext().publishEvent(new BusinessFocusEvent("focusBusiness",bmsBusiness,userId));
    }

    public Map<String, Object> findBusinessVideo(String userId,Integer businessId,Integer pageNum,
                                                        Integer pageSize,String latitude,String longitude) {

        Optional<BmsBusiness> bmsBusinessOp = bmsbusinessDao.findById(businessId);
        if(!bmsBusinessOp.isPresent()){
            return ResultMapHelper.failure("获取失败,该店铺不存在！");
        }
        Pageable pageable = PageRequest.of(pageNum - 1,pageSize, Sort.Direction.DESC,"isTop","topTime","newTime");
        List<BmsVideo> bmsVideos = this.findBusinessVideoToUserClient(userId,businessId,latitude,longitude,pageable);
        if(bmsVideos != null){
            for(BmsVideo bmsVideo : bmsVideos){
                if(bmsVideo.getId().intValue() == 988){
                    System.out.println(".......................找到了..........");
                }
            }
        }
        return ResultMapHelper.success(bmsVideos, ResultMsg.MSG_GET_SUCCESS);
    }

    public List<BmsVideo> findBusinessVideoToUserClient(String userId,Integer businessId,String latitude,
                                            String longitude,Pageable pageable){
        List<BmsVideo> bmsVideos = bmsVideoService.findByBmsId(businessId,pageable);
        Set videoIds = bmsVideoService.getVideoIds(bmsVideos);
        bmsVideoService.calculatedDistance(bmsVideos, latitude, longitude);
        bmsVideoService.setUserLikeAndFoot(userId,bmsVideos,videoIds);
        bmsVideoService.setVideoStatic(bmsVideos);
        bmsVideoService.setVideoComment(bmsVideos,videoIds);
        bmsVideoService.setSendMes(bmsVideos,videoIds);
        bmsVideoService.setIsOpenCouponAndGroupBuy(bmsVideos);
        return bmsVideos;
    }

    public Map<String, Object> checkIsChangeVendorName(Integer businessId){
        final int vendorChangeTime = 6;
        Optional<BmsBusiness> bmsBusinessOptional = bmsbusinessDao.findById(businessId);
        if(!bmsBusinessOptional.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST,"店铺不存在");
        }
        BmsBusiness bmsBusiness = bmsBusinessOptional.get();
        if(bmsBusiness.getVendorNameUpdateTime() != null){
            Date updateVendorNameTime = bmsBusiness.getVendorNameUpdateTime();
            //判断当前时间开始是否超过半年
            Date nowDate = new Date();
            Date toTime = DateTimeUtils.getYearMonth(updateVendorNameTime,vendorChangeTime);
            if(toTime.getTime() >= nowDate.getTime()){
                return ResultMapHelper.failure("");
            }
        }
        return ResultMapHelper.success();
    }

    public BmsBusiness getBusinessById(Integer businessId){
        return bmsbusinessDao.findByIdAndIsDelete(businessId,Constants.COMMON_FLAG_FALSE_INT);
    }

    public Map<String, Object> recommendHotBusiness(BusinessReDto businessReDto) {
        final int businessSize = 500;
        List<BmsBusiness> bmsBusinessesChooses = new LinkedList<>();
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("isUnload",Constants.COMMON_FLAG_FALSE_INT);
        if(StringUtils.isNotBlank(businessReDto.getAddrCity()) &&
                StringUtils.isNotBlank(businessReDto.getAddrDistinct()) && StringUtils.isNotBlank(businessReDto.getLatitude())
        && StringUtils.isNotBlank(businessReDto.getLongitude())){
            //查询当去地区店铺
            conditionMap.put("addrCity",businessReDto.getAddrCity());
            conditionMap.put("addrDistrict",businessReDto.getAddrDistinct());
            Pageable pageable = BmsCommonService.getPageable(1,businessSize, Sort.Direction.DESC,"dkTimes");
            List<BmsBusiness> bmsBusinesses = bmsbusinessDao.findAll(new SpecificationUtils(conditionMap),pageable).getContent();
            //找出最近的
            String[] selfDistances = new String[]{"3","5","10","20"};
            if(bmsBusinesses != null & bmsBusinesses.size() > 0) {
                outterLoop : for (String dis : selfDistances) {
                    double selfDis = Double.parseDouble(dis) * 1000;
                    for (BmsBusiness business : bmsBusinesses) {
                        //公里数以内
                        if (StringUtils.isNotBlank(business.getLatitude()) && StringUtils.isNotBlank(business.getLongitude())){
                            double lat = Double.parseDouble(business.getLatitude());
                            double lnt = Double.parseDouble(business.getLongitude());
                            double distance = LocationUtils.getDistance(lat, lnt, Double.parseDouble(businessReDto.getLatitude()), Double.parseDouble(businessReDto.getLongitude()));
                            if (distance < selfDis) {
                                bmsBusinessesChooses.add(business);
                            }
                            if (bmsBusinessesChooses.size() == businessReDto.getPageSize()) {
                                break outterLoop;
                            }
                        }
                    }
                }
            }
            //补齐
            if(bmsBusinessesChooses.size() < businessReDto.getPageSize()){
                bmsBusinessesChooses.addAll(getHotBusiness(bmsBusinessesChooses.size(),conditionMap,businessReDto));
            }
        }else {
            //直接找出热门的商家数个数
            bmsBusinessesChooses = getHotBusiness(0,conditionMap,businessReDto);
        }
        setLabels(bmsBusinessesChooses);
        return ResultMapHelper.success(bmsBusinessesChooses);
    }

    private List<BmsBusiness> getHotBusiness(Integer pageSize,Map<String,Object> conditionMap,BusinessReDto businessReDto){
        Long countNum = bmsbusinessDao.count(new SpecificationUtils(conditionMap));
        Double pageNums = Math.floor(countNum.doubleValue() / businessReDto.getPageSize());
        Integer pageNum = (int)(Math.random() * pageNums.intValue());
        Pageable pageable = BmsCommonService.getPageable(pageNum,businessReDto.getPageSize() - pageSize,Sort.Direction.DESC,"dkTimes");
        return bmsbusinessDao.findAll(new SpecificationUtils(conditionMap),pageable).getContent();
    }

    public void setLabels(List<BmsBusiness> bmsBusinesses){
        if(bmsBusinesses.size() > 0){
            Set labelSet = new HashSet();
            for(BmsBusiness business : bmsBusinesses){
                if(StringUtils.isNotBlank(business.getLabel())){
                    labelSet.add(business.getLabel());
                }
            }
            Map<String,BmsBusinessLabel> labelMap = new HashMap<>();
            if(labelSet.size() > 0){
                //查询出labelId
                List<BmsBusinessLabel> bmsBusinessLabels = bmsBusinessLabelService.getBaseDao().findByLabelNameInAndIsDelete(labelSet,Integer.parseInt(Constants.COMMON_FLAG_FALSE));
                if(bmsBusinessLabels != null && bmsBusinessLabels.size() > 0){
                    for(BmsBusinessLabel bmsBusinessLabel : bmsBusinessLabels) {
                        labelMap.put(bmsBusinessLabel.getLabelName(),bmsBusinessLabel);
                    }
                }
            }
            for(BmsBusiness business : bmsBusinesses){
                if(StringUtils.isNotBlank(business.getLabel())){
                    String label = business.getLabel();
                    if(labelMap.containsKey(label)){
                        business.setLabelId(labelMap.get(label).getId());
                    }
                }
            }
        }
    }

    public List<Map<String,Object>> findBusinessByLocation(String addrCity, String addrDistrict,Set businessId) {
        return bmsbusinessDao.findByLocation(addrCity,addrDistrict,businessId);
    }

    public Set<Integer> getBusinessIdsByByAddrCityAndAddrDistrict(String addrCity, String addrDistrict) {
        Set<Integer> buinessIds = new HashSet<>();
        List<Map<String, Object>> bmsIdsMap = findByAddrCityAndAddrDistrict(addrCity,addrDistrict);
        if(bmsIdsMap!= null && bmsIdsMap.size() > 0){
            for (Map<String, Object> bmsBusiness : bmsIdsMap) {
                buinessIds.add(Integer.parseInt(bmsBusiness.get("id").toString()));
            }
        }
        return buinessIds;
    }

    public List<Map<String, Object>> findByAddrCityAndAddrDistrict(String addrCity, String addrDistrict) {
        StringBuilder stringBuilder = new StringBuilder(Constants.REDIS_KEY_PREFIX + "business:idAndGps");
        if(!"".equals(addrCity)){
            String areaCode = String.valueOf(addrCity.hashCode()).substring(0,4);
            stringBuilder.append(":" + areaCode);
            if(!"".equals(addrDistrict)){
                String district = String.valueOf(addrDistrict.hashCode()).substring(0,4);
                stringBuilder.append(":" + district);
            }
        }
        String redisKey = stringBuilder.toString();
        List<Map<String, Object>> bmsBusinesses;
        if(redisTemplate.hasKey(redisKey)){
            //从缓存中获取
            bmsBusinesses = (List<Map<String, Object>>) redisTemplate.opsForValue().get(redisKey);
        }else {
            bmsBusinesses = bmsbusinessDao.findByAddrCityToFrontShow(addrCity,addrDistrict,Constants.COMMON_FLAG_FALSE_INT,
                    Constants.COMMON_FLAG_FALSE_INT);
            List<Map<String,Object>> redisData = new LinkedList<>();
            if(bmsBusinesses != null & bmsBusinesses.size() > 0) {
                for(Map<String,Object> objectMap : bmsBusinesses){
                    Map<String,Object> videoLatLngMap = new HashMap<>();
                    videoLatLngMap.put("id",objectMap.get("id"));
                    videoLatLngMap.put("latitude",objectMap.get("latitude"));
                    videoLatLngMap.put("longitude",objectMap.get("longitude"));
                    redisData.add(videoLatLngMap);
                }
                redisTemplate.opsForValue().set(redisKey,redisData,12, TimeUnit.HOURS);
            }
        }
        return bmsBusinesses;
    }


    public void calculatedDistance(List<BmsBusiness> bmsBusinesses, String latitude, String longitude) {
        if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
            if (bmsBusinesses != null && bmsBusinesses.size() > 0) {
                for (BmsBusiness bmsBusiness : bmsBusinesses) {
                    if (StringUtils.isNotBlank(bmsBusiness.getLatitude()) && StringUtils.isNotBlank(bmsBusiness.getLongitude())) {
                        double lat = Double.parseDouble(bmsBusiness.getLatitude());
                        double lnt = Double.parseDouble(bmsBusiness.getLongitude());
                        double distance = Math.ceil(LocationUtils.getDistance(lat, lnt, Double.parseDouble(latitude), Double.parseDouble(longitude)));
                        bmsBusiness.setDistance(distance);
                    }
                }
            }
        }
    }


    public void setIsOpenCouponAndGroupBuy(List<BmsBusiness> bmsBusinesses) {
        //设置是否开通优惠买单和团购券
        //查询是否开通优惠买单
        Set<Integer> businessIds = new HashSet<>();
        if(bmsBusinesses != null && bmsBusinesses.size() >0){
            for(BmsBusiness business : bmsBusinesses) {
                businessIds.add(business.getId());
            }
            Map<Integer,Integer> bmsDxOpenMap = bmsDxCouponService.checkIsOpenCoupon(businessIds);
            Map<Integer,Integer> bmsGroupBuyOpenMap = bmsDxGroupBuyService.checkIsOpenGroupBuy(businessIds);
            for(BmsBusiness business : bmsBusinesses) {
                if(bmsDxOpenMap.containsKey(business.getId())){
                    business.setIsOpenCoupon(Constants.COMMON_FLAG_TRUE_INT);
                    business.setIsOpenOrder(Constants.COMMON_FLAG_TRUE_INT);
                }
                if(bmsGroupBuyOpenMap.containsKey(business.getId())){
                    business.setIsOpenGroupBuy(Constants.COMMON_FLAG_TRUE_INT);
                    business.setIsOpenOrder(Constants.COMMON_FLAG_TRUE_INT);
                }
            }
            bmsbusinessDao.saveAll(bmsBusinesses);
        }
    }

    public void sortByDistance(List<BmsBusiness> bmsBusinesses){
        if(bmsBusinesses != null && bmsBusinesses.size() > 0){
            Collections.sort(bmsBusinesses, new Comparator<BmsBusiness>() {
                @Override
                public int compare(BmsBusiness o1, BmsBusiness o2) {
                    if(o1.getDistance() > o2.getDistance()) {
                        return 1;
                    }else if(o1.getDistance() == o2.getDistance()){
                        return 0;
                    }
                    return -1;
                }
            });
        }
    }

    public void getDefaultRecommendLevel(List<BmsBusiness> recommendBmsBusiness) {
        Pageable pageable = BmsCommonService.getPageable(1,10 - recommendBmsBusiness.size(), Sort.Direction.DESC,"dkTimes");
        recommendBmsBusiness.addAll(bmsbusinessDao.findAll(pageable).getContent());
    }

    public Set<Integer> findBusinessByLabel(String searchText) {
        Set<Integer> businessIds = new HashSet<>();
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isUnload",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("isAuth",Constants.COMMON_FLAG_TRUE_INT);
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("label_LIKE",searchText);
        List<BmsBusiness> bmsBusinesses = bmsbusinessDao.findAll(new SpecificationUtils(conditionMap));
        if(bmsBusinesses != null && bmsBusinesses.size() > 0){
            businessIds.addAll(bmsBusinesses.stream().map(BmsBusiness::getId).collect(Collectors.toSet()));
        }
        return businessIds;
    }

    public Set<Integer> findBusinessByVendorName(String searchText) {
        Set<Integer> businessIds = new HashSet<>();
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isUnload",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("isAuth",Constants.COMMON_FLAG_TRUE_INT);
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("vendorName_LIKE",searchText);
        List<BmsBusiness> bmsBusinesses = bmsbusinessDao.findAll(new SpecificationUtils(conditionMap));
        if(bmsBusinesses != null && bmsBusinesses.size() > 0){
            businessIds.addAll(bmsBusinesses.stream().map(BmsBusiness::getId).collect(Collectors.toSet()));
        }
        return businessIds;
    }

    public List<BmsBusiness> sortByIsOpenOrder(List<BmsBusiness> recommendBmsBusiness) {
        List<BmsBusiness> bmsBusinesses = new LinkedList<>();
        List<BmsBusiness> otherBmsBusiness = new LinkedList<>();
        if(recommendBmsBusiness != null && recommendBmsBusiness.size() > 0){
            for(BmsBusiness bmsBusiness : recommendBmsBusiness){
                if(bmsBusiness.getIsOpenCoupon() != null && bmsBusiness.getIsOpenCoupon() == Constants.COMMON_FLAG_TRUE_INT){
                    bmsBusinesses.add(bmsBusiness);
                    continue;
                }
                if(bmsBusiness.getIsOpenGroupBuy() != null && bmsBusiness.getIsOpenGroupBuy() == Constants.COMMON_FLAG_TRUE_INT){
                    bmsBusinesses.add(bmsBusiness);
                    continue;
                }
                otherBmsBusiness.add(bmsBusiness);

            }
        }
        bmsBusinesses.addAll(otherBmsBusiness);
        return bmsBusinesses;
    }

    public Set<Integer> findBusinessIdByCircle(String businessCircle) {
        List<String> businessCircleIds = (List<String>) JSON.parse(businessCircle);
        Set<Integer> bcIds = new HashSet<>();
        if(businessCircleIds.size() > 0){
            for(String b : businessCircleIds){
                bcIds.add(Integer.parseInt(b));
            }
        }
        if(bcIds.size() == 0){
            return bcIds;
        }
        List<BmsBusiness> bmsBusinesses = bmsbusinessDao.findBusinessByCircle(bcIds);
        return bmsBusinesses.stream().map(BmsBusiness::getId).collect(Collectors.toSet());
    }

    public Set<Integer> findOnlineBusinessIds() {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isDelete",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("isAuth",Constants.COMMON_FLAG_TRUE_INT);
        conditionMap.put("isUnload",Constants.COMMON_FLAG_FALSE_INT);
        List<BmsBusiness> bmsBusinesses = bmsbusinessDao.findAll(new SpecificationUtils(conditionMap));
        return bmsBusinesses.stream().map(BmsBusiness::getId).collect(Collectors.toSet());
    }

    public Set<Integer> findBusinessIdByAddr(String addrParentCity, String addCity) {
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("addrCity",addrParentCity);
        conditionMap.put("addrDistrict",addCity);
        conditionMap.put("isAuth",Constants.COMMON_FLAG_TRUE_INT);
        conditionMap.put("isUnload",Constants.COMMON_FLAG_FALSE_INT);
        List<BmsBusiness> bmsBusinesses = bmsbusinessDao.findAll(new SpecificationUtils(conditionMap));
        return bmsBusinesses.stream().map(BmsBusiness::getId).collect(Collectors.toSet());
    }

    public List<BmsBusiness> getVendorNameOrderByDistance(String searchText, String longitude,
                                                          String latitude,Integer pageNum,Integer pageSize) {
        int start = (pageNum - 1) * pageSize;
        int end = start + pageSize;
        return bmsbusinessDao.getVendorNameOrderByDistance(searchText,longitude,latitude,start,end);
    }

    public void test() {
        String driver = "com.mysql.jdbc.Driver";
        /*String url = "jdbc:mysql://168.168.3.187:3306/ubms?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2b8";
        String user = "root";
        String password = "123456";*/
        String url = "jdbc:mysql://127.0.0.1:3306/ubms?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2b8";
        String user = "root";
        String password = "root";
        /*String url = "jdbc:mysql://cdb-pq00uokv.gz.tencentcdb.com:10046/ub?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2b8";
        String user = "syni_cloud";
        String password = "ltserver123#";*/
        String sql = "select count(id) num from bms_business where is_delete = 0 and is_unload = 0 and vendor_name like '%火锅%' ";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            //注册数据库驱动
            Class.forName(driver);
            //取得数据库连接
            conn = DriverManager.getConnection(url, user, password);
            //进行预编译，这里进行参数设置
            pstmt = conn.prepareStatement(sql);
            //进行编译
            rs = pstmt.executeQuery();
            while (rs.next()) {
                int a = rs.getInt("num");
                System.out.println(a);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            if (rs != null) {//轻量级，创建和销毁rs所需要的时间和资源较小
                try {
                    rs.close();
                } catch (Exception e) {
                    log.error(e.getMessage(),e);
                }
            }
            if (conn != null) {//重量级，创建和销毁rs所需要的时间和资源较小
                try {
                    conn.close();
                } catch (Exception e) {
                    log.error(e.getMessage(),e);
                }
            }
        }
    }
}
